package com.teacher.controller;


import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.teacher.auto.JSONAuthentication;
import com.teacher.entity.CollegeMajor;
import com.teacher.entity.TUser;
import com.teacher.mapper.CollegeMajorMapper;
import com.teacher.mapper.TUserMapper;
import com.teacher.mapper.TXjMapper;
import com.teacher.response.Result;
import com.teacher.utils.VerifyCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author teacher
 * @since 2022-04-09
 */
@RestController
@RequestMapping("/t-user")
public class TUserController extends JSONAuthentication {

    public static Map<String, Object> contextMap=new HashMap<String,Object>();
    @Autowired
    TUserMapper tUserMapper;
    @Autowired
    CollegeMajorMapper collegeMajorMapper;
    @Autowired
    TXjMapper tXjMapper;
    @ApiOperation(value = "获取验证码")
    @GetMapping("/vercode")
    public void code(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("image/png");
        VerifyCode vc = new VerifyCode();
        BufferedImage image = vc.getImage();
        String text = vc.getText();
        HttpSession session = req.getSession();
        session.setAttribute("index_code", text);
        contextMap.put("code",text);

        VerifyCode.output(image, resp.getOutputStream());
    }
    @ApiOperation(value = "添加用户")
    @PostMapping("/add")
    public void addCar(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("password") String password,@RequestParam("role")String role) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("username",username);
        TUser baMeans1=tUserMapper.selectOne(wrapper);
        if(baMeans1!=null){
            Result error = Result.error().message("该用户名已被占用");
            this.WriteJSON(request, response, error);
        }else{
            TUser yUser=new TUser();
            yUser.setUsername(username);
            String password1 = new BCryptPasswordEncoder().encode(password);
            yUser.setPassword(password1);
            yUser.setRole(role);
            if(tUserMapper.insert(yUser)>0){
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            }else{
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }
    }
    @ApiOperation(value = "删除用户")
    @PostMapping("/del")
    public void delUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("userId") int userId) throws Exception {
        int i = tUserMapper.deleteById(userId);
        if (i > 0) {
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "修改密码")
    @PostMapping("/updPassword")
    public void updUser(HttpServletRequest request, HttpServletResponse response, @RequestParam("password") String password, @RequestParam("rpassword") String rpassword, @RequestParam("id") int id) throws Exception {
        TUser shUser = tUserMapper.selectById(id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(password, shUser.getPassword())) {
            String newPassword = new BCryptPasswordEncoder().encode(rpassword);
            shUser.setPassword(newPassword);
            if (tUserMapper.updateById(shUser) > 0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        } else {
            Result error = Result.error();
            error.setMessage("密码不正确");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过学号或者工号查找用户")
    @PostMapping("/findByName")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("username") String username, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("username", username);
        Page<TUser> shUserPage = new Page<>(current, size);
        Page<TUser> shUserPages = tUserMapper.selectPage(shUserPage, wrapper);
        List<TUser> records = shUserPages.getRecords();
        for (TUser a: records){
            if(a.getCmId()!=null)
                a.setCollegeMajor(collegeMajorMapper.selectById(a.getCmId()));
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("sfz",a.getSfz());
            if(tXjMapper.selectOne(wrapper1)!=null){
                a.setTXj(tXjMapper.selectOne(wrapper1));
            }
        }
        int total = tUserMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有用户")
    @PostMapping("/findAllUser")
    public void findById(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        Page<TUser> shUserPage = new Page<>(current, size);
        Page<TUser> shUserPages = tUserMapper.selectPage(shUserPage, null);
        List<TUser> records = shUserPages.getRecords();
        for (TUser a: records){
            if(a.getCmId()!=null)
                a.setCollegeMajor(collegeMajorMapper.selectById(a.getCmId()));
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("sfz",a.getSfz());
            if(tXjMapper.selectOne(wrapper1)!=null){
                a.setTXj(tXjMapper.selectOne(wrapper1));
            }
        }
        int total = tUserMapper.selectCount(null);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }

    @ApiOperation(value = "通过id查找用户")
    @PostMapping("/findByUserId")
    public void findByUserId(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws Exception {
        TUser shUser = tUserMapper.selectById(id);
        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("sfz",shUser.getSfz());
        if(tXjMapper.selectOne(wrapper1)!=null){
            shUser.setTXj(tXjMapper.selectOne(wrapper1));
        }
        if(shUser.getCmId()!=null){
            shUser.setCollegeMajor(collegeMajorMapper.selectById(shUser.getCmId()));
        }
        if (shUser != null) {
            Result ok = Result.ok().data("user", shUser);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "通过id查找用户设置学院和专业")
    @PostMapping("/findByUserIdSzZy")
    public void findByUserIdSzZy(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id,@RequestParam("major")String major ) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("major",major);
        CollegeMajor collegeMajor = collegeMajorMapper.selectOne(wrapper);
        if(collegeMajor!=null){

            TUser shUser = tUserMapper.selectById(id);
            shUser.setCmId(collegeMajor.getId());
            if (tUserMapper.updateById(shUser)>0) {
                Result ok = Result.ok();
                this.WriteJSON(request, response, ok);
            } else {
                Result error = Result.error();
                this.WriteJSON(request, response, error);
            }
        }else{
            Result error = Result.error().message("不存在该专业");
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "添加用户资料")
    @PostMapping("/addUserMean")
    public void addUserMean(HttpServletRequest request, HttpServletResponse response, @RequestBody TUser tUser) throws Exception {
        TUser tUser1 = tUserMapper.selectById(tUser.getId());
        tUser1.setName(tUser.getName());
        tUser1.setPhone(tUser.getPhone());
        tUser1.setSfz(tUser.getSfz());
        tUser1.setYouxiang(tUser.getYouxiang());
        if(tUser.getCmId()!=null) {
            tUser1.setCmId(tUser.getCmId());
        }
        if(tUserMapper.updateById(tUser1)>0){
            Result ok = Result.ok();
            this.WriteJSON(request, response, ok);
        }else{
            Result error = Result.error().message("添加失败");
            this.WriteJSON(request, response, error);
        }

    }
    @ApiOperation(value = "查找所有老师")
    @PostMapping("/findAllTeacher")
    public void findAllTeacher(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("role","教师");
        Page<TUser> shUserPage = new Page<>(current, size);
        Page<TUser> shUserPages = tUserMapper.selectPage(shUserPage, wrapper);
        List<TUser> records = shUserPages.getRecords();
        for (TUser a: records){
            if(a.getCmId()!=null)
                a.setCollegeMajor(collegeMajorMapper.selectById(a.getCmId()));
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("sfz",a.getSfz());
            if(tXjMapper.selectOne(wrapper1)!=null){
                a.setTXj(tXjMapper.selectOne(wrapper1));
            }
        }
        int total = tUserMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
    @ApiOperation(value = "查找所有学生")
    @PostMapping("/findAllStudent")
    public void findAllStudent(HttpServletRequest request, HttpServletResponse response, @RequestParam("size") int size, @RequestParam("current") int current) throws Exception {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("role","学生");
        Page<TUser> shUserPage = new Page<>(current, size);
        Page<TUser> shUserPages = tUserMapper.selectPage(shUserPage, wrapper);
        List<TUser> records = shUserPages.getRecords();
        for (TUser a: records){
            if(a.getCmId()!=null)
                a.setCollegeMajor(collegeMajorMapper.selectById(a.getCmId()));
            QueryWrapper wrapper1=new QueryWrapper();
            wrapper1.eq("sfz",a.getSfz());
            if(tXjMapper.selectOne(wrapper1)!=null){
                a.setTXj(tXjMapper.selectOne(wrapper1));
            }
        }
        int total = tUserMapper.selectCount(wrapper);
        if (records.size() > 0) {
            Result ok = Result.ok().data("userList", records).data("total", total);
            this.WriteJSON(request, response, ok);
        } else {
            Result error = Result.error();
            this.WriteJSON(request, response, error);
        }
    }
}

